<template>
    <div class="exam-management" style="width:80%;height:80%">
        
        <div class="search">
             <!-- 考试名称输入框 -->
            <div class="select-group">
                <label>考试名称 </label>
                <input type="text" v-model="exam.name" placeholder="请输入" style="height: 28px;width:280px"/>
            </div>
  
             <!-- 时间选择 -->
             <div class="select-group">
                <label>从 </label>
                <input type="date" v-model="exam.startTime" style="height: 28px;width:150px"/>
                <label> 至 </label>
                <input type="date" v-model="exam.endTime" style="height: 28px;width:150px"/>
            </div>


              <el-button type="primary" plain @click="searchExam(exam.id)" class="search-button">查询</el-button>
     <!--            <button @click="searchExam(exam.id)">查询</button> -->
           
        </div>

      <div v-if="exams && exams.length > 0">
        <!-- 考试列表 -->
        <div class="exam-list">
          <div v-for="(item, index) in exams" :key="index" class="exam-item">
            <div class="exam-info">
              <div class="exam-title">{{ item.name }}</div>
              <span>考试开始时间:{{ item.startTime }} </span>
              <span> 考试结束时间:{{ item.endTime }}</span>
              <span> 时限:{{ item.duration }}分钟</span>
              <!-- <div class="exam-status">{{ item.state }}</div> -->
              <div class="remind">
                考试注意点:
                <ol>
                  <li>本次考试为线上闭卷考试</li>
                  <li>本次考试不允许提前进入！</li>
                  <li>考试开始时间10分钟后不进入考试即无法再进入考试，本次考试直接判零分！</li>
                </ol>
              </div>  
            </div>
            <div class="exam-actions">
              <button @click="viewExam(item.id)">查看成绩</button>
            </div>
          </div>
        </div>
        
        <!-- 分页组件 -->
        <div class="pagination">
          <button @click="prevPage" :disabled="currentPage === 1">&lt;</button>
          <button v-for="page in totalPages" :key="page" @click="goToPage(page)" :class="{ active: page === currentPage }">{{ page }}</button>
          <button @click="nextPage" :disabled="currentPage === totalPages">&gt;</button>
        </div>
      </div>
      <div v-else class="noData">
        <img src="@/assets/img/noDataView.png" alt="No Data Found"/>
      </div>  
      
    </div>
  </template>
  <script setup>
  import { ref, reactive, computed ,onMounted} from 'vue';
  import { useRouter } from 'vue-router';
  import { interceptor } from '@/utils/interceptor';
  import { formatDateToYMD } from '@/utils/dateUtil';

  const router = useRouter()
  
  onMounted(()=>{
    searchExam();
  })
  
  // 定义一个响应式的 exam 对象用于存储搜索条件
  const exam = reactive({
      name: '',
      startTime: '',
      endTime: '',
      page: 1,
      pageSize: 4,
      teacherId:''
  });
  
  // 当前页码
  const currentPage = ref(1);
  
  // 总记录数，用于计算总页数
  const totalRecords = ref(0);
  
  // 定义 exams 为一个响应式的引用类型，用于存储考试列表数据
  const exams = ref([]);
  
  // 使用计算属性来计算总页数
  const totalPages = computed(() => {
      return Math.ceil(totalRecords.value / exam.pageSize);
  });
  
  // 搜索考试的方法
  const searchExam = () => {
      // 更新当前页码到 exam 对象
      exam.page = currentPage.value;
  
      // 清空旧的 exams 数据
      exams.value = [];

     // const formattedStartTime = exam.startTime ? formatDate(new Date(exam.startTime)) : null;
      //const formattedEndTime = exam.endTime ? formatDate(new Date(exam.endTime)) : null;

      const httpInstance = interceptor()
      httpInstance.post("/teacher/exam/page", {
          name: exam.name,
          state: 3,
          startTime: exam.startTime,
          endTime: exam.endTime,
          page: exam.page,
          pageSize: exam.pageSize,
          teacherId: localStorage.getItem("user-id")
      }).then((res) => {
        //console.log("res",res.data.data.records)
          // 假设返回的数据结构包含 records 和 total 字段
          if (res.data && res.data.code === 1 && Array.isArray(res.data.data.records)) {
            exams.value = res.data.data.records.map(exam => ({
                id: exam.id,
                name: exam.name,
                duration: exam.duration,
                startTime: formatDateToYMD(exam.startTime),
                endTime: formatDateToYMD(exam.endTime),
                // 其他需要映射的字段...
            }));
            // 使用examList... 
            totalRecords.value = res.data.data.total; // 更新总条目数 */
            //console.log("totalRecords:", totalRecords.value);
            //console.log("Exam List:", examList.value);
         } else {
            console.warn("Invalid response structure or no records found");
        }
      }).catch(error => {
          console.error("查询考试失败:", error);
      });
  
     
  };
  
  // 分页相关的方法
  const prevPage = () => {
      if (currentPage.value > 1) {
          currentPage.value--;
          searchExam();
      }
  };
  
  const nextPage = () => {
      if (currentPage.value < totalPages.value) {
          currentPage.value++;
          searchExam();
      }
  };
  
  const goToPage = (page) => {
      if (page >= 1 && page <= totalPages.value) {
          currentPage.value = page;
          searchExam();
      }
  };
  
  //查看成绩
  const viewExam = (id) => {
    
    console.log("id:",id)
    router.push({
        name:'score',
        params: {examId: id}
    })
  }

  </script>
  
  <style scoped>
    .noData img{
     max-width:100%;
     height:auto;
     
     margin-left:-20%;
  }
  .exam-management {
    padding: 50px;
    width:90%;
    margin:auto;
  }
  
  .search{
    display: flex;
  }

  .select-group {
    margin-bottom: 10px;
    margin-left: 20px;
    margin-right: 5px;
  }

  .select-group label{
    font-size:20px;
    color: #333;
  }

  .search-button {
    margin-top: 5px;
    margin-left:8px;
    height: 28px;
    font-size:17px;

}

  
  .exam-list {
    margin-top: 20px;
  }
  
  .exam-item {
    border: 1px solid #ccc;
    padding: 10px;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.3);
    border-radius: 8px;
    height:150px;
  }

  .exam-title{
    font-size: 22px;
    font-weight: bold;
  }


  .remind{
  font-size:12px;
  color:#878282;
}

  .pagination{
  display: flex;
  /* width:100%; */
  justify-content: center;
}
  
  .pagination button {
    margin: 0 5px;
  }
  
  .active {
    background-color: #007bff;
    border:none;
    color: white;
  }
  </style>